package com.fs.controller.v2;

import com.fs.controller.vo.PageData;
import com.fs.controller.vo.friend.*;
import com.fs.global.init.RoleName;
import com.fs.realm.UserContext;
import com.fs.service.FriendService;
import com.fs.service.bo.BoPageInfo;
import com.fs.service.bo.friend.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(tags="朋友信息",description = "小程序用户使用")
@RequestMapping("/v2/friends")
@RequiresRoles(RoleName.CUSTOMER)
@Validated
public class FriendController {

    private final FriendService friendService;

    public FriendController(FriendService friendService) {
        this.friendService = friendService;
    }

    @ApiOperation("创建朋友")
    @PostMapping
    public RespFriend createFriend(@RequestBody @Valid ReqAddFriend req) {
        int customerID = UserContext.getPrinciple();
        BoCreateParam param = new BoCreateParam().setName(req.getName()).setPhone(req.getPhone()).setCustomerID(customerID);
        BoFriend boFriend = friendService.createFriend(param);
        return new RespFriend(boFriend);
    }

    @ApiOperation("更新朋友信息")
    @PutMapping
    public void updateFriendById(@RequestBody @Valid ReqUpdateFriend req) {
        BoUpdateParam boUpdateParam = new BoUpdateParam().setFriendId(req.getFriendId()).setName(req.getName())
                .setPhone(req.getPhone());

        Integer updateResult = friendService.updateFriendById(boUpdateParam);
        if (updateResult != 1) {
            throw new UpdateFriendException();
        }
    }

    @ApiOperation("删除朋友")
    @DeleteMapping("/{friendId}")
    public void deleteFriend(@PathVariable int friendId) {
        friendService.deleteFriend(friendId);
    }

    @ApiOperation("小程序用户分页查询自己的朋友,分页参数")
    @GetMapping
    public PageData<RespFriend> findFriendsByCustomer(@RequestParam int pageNo, @RequestParam int pageSize) {
        int customerId = UserContext.getPrinciple();
        QueryFriendParam queryParam = new QueryFriendParam().setCustomerId(customerId);
        BoPageInfo<BoFriendWithCustomer> boFriends = friendService.query(queryParam, pageNo, pageSize);

        List<RespFriend> results = boFriends.getResults().stream()
                .map(RespFriend::new).collect(Collectors.toList());
        return new PageData<>(results ,boFriends.getTotal());
    }
}
